package pwaf.server;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import pwaf.client.Album;
import pwaf.client.AlbumsService;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.geo.Point;
import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class AlbumsServiceImpl extends RemoteServiceServlet implements AlbumsService {

	@Override
	public List<Album> getAlbums(String user) throws Exception {
		PicasawebService pws = new PicasawebService("Picasa Web Albums Frontpage");

		URL albumsUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + user + "?kind=album");
		UserFeed albumsFeed = pws.getFeed(albumsUrl, UserFeed.class);

		List<Album> albums = new ArrayList<Album>();
		for (AlbumEntry albumEntry : albumsFeed.getAlbumEntries()) {
			Album album = new Album();
			album.title = albumEntry.getTitle().getPlainText();
			MediaThumbnail albumThumbnail = albumEntry.getMediaThumbnails().get(0);
			album.thumbnail = albumThumbnail.getUrl();
			album.thumbnailWidth = albumThumbnail.getWidth();
			album.thumbnailHeight = albumThumbnail.getHeight();
			album.path = albumEntry.getUsername() + "/" + albumEntry.getName();
			Point geoLocation = albumEntry.getGeoLocation();
			if (geoLocation != null) {
				album.hasLatLng = true;
				album.lat = geoLocation.getLatitude();
				album.lng = geoLocation.getLongitude();
			} else {
				album.hasLatLng = false;
			}

			// URL photosURL = new URL("https://picasaweb.google.com/data/feed/api/user/" + user + "/albumid/" +
			// album.id);
			// AlbumFeed photosFeed = pws.getFeed(photosURL, AlbumFeed.class);
			// for (PhotoEntry photoEntry : photosFeed.getPhotoEntries()) {
			// Photo photo = new Photo();
			// photo.id = photoEntry.getId();
			// album.photos.add(photo);
			// }

			albums.add(album);
		}

		return albums;
	}
}
